package com.example.music_liwei.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.FragmentManager;
import androidx.palette.graphics.Palette;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.example.music_liwei.R;
import com.example.music_liwei.adapter.FragmentViewPagerAdapter;
import com.example.music_liwei.adapter.MusicListAdapter;
import com.example.music_liwei.bean.ResponseData;
import com.example.music_liwei.messageEvent.MessageEvent;
import com.example.music_liwei.messageEvent.MessageEventCurrentIndexBoolean;
import com.example.music_liwei.messageEvent.MessageEventSeekbar;
import com.google.android.material.navigation.NavigationView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class MusicPlayerActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "ning";
    private List<ResponseData.MusicInfo> musicInfoList = new ArrayList<>();
    private MediaPlayer mediaPlayer;
    private int currentIndex = 0;
    private boolean isPause = false;
    private int playMode = 0; // 0: 顺序播放, 1: 随机播放, 2: 单曲循环

    private ImageView ivCover, ivPlayPause, ivNext, ivPrev, ivLoop, ivMenu;
    private TextView tvMusicName, tvAuthor, tvCurrentTime, tvTotalTime, tvPlayMode;
    private SeekBar seekBar;
    private boolean isSeekBarChanging = false;
    private boolean isXin = false;
    private Handler handler = new Handler();
    private ImageView iv_back;
    private ImageView iv_xin;
    private DrawerLayout drawerLayout;
    private NavigationView navigationView;
    private TextView tvMusicCount;
    private RecyclerView rvMusicList;
    private MusicListAdapter musicListAdapter;

    private float initialY;
    private boolean isDraggingDown = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music_player);

        EventBus.getDefault().register(this);

        // 设置跟随系统的主题模式
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);

        initViews();

        mediaPlayer = new MediaPlayer();

        ivPlayPause.setOnClickListener(v -> togglePlayPause());
        ivNext.setOnClickListener(v -> playNext());
        ivPrev.setOnClickListener(v -> playPrev());
        ivLoop.setOnClickListener(v -> switchPlayMode());
        ivMenu.setOnClickListener(v -> drawerLayout.openDrawer(navigationView));

        // 初始化 ViewPager 和 Fragment
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentViewPagerAdapter fragmentViewPagerAdapter = new FragmentViewPagerAdapter(fragmentManager);
        ViewPager viewPager = findViewById(R.id.vp_show);
        viewPager.setAdapter(fragmentViewPagerAdapter);

        // 给进度条加的点击事件
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser && mediaPlayer != null) {
                    mediaPlayer.seekTo(progress);
                    tvCurrentTime.setText(formatTime(progress));
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                isSeekBarChanging = true;
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                isSeekBarChanging = false;
                if (mediaPlayer != null) {
                    mediaPlayer.seekTo(seekBar.getProgress());
                }
            }
        });

        mediaPlayer.setOnCompletionListener(mp -> onSongComplete());

        if (musicInfoList != null && !musicInfoList.isEmpty()) {
            playMusic(currentIndex);
        }

        // 设置滑动监听
        findViewById(R.id.activity_music_player).setOnTouchListener((v, event) -> {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    initialY = event.getY();
                    break;
                case MotionEvent.ACTION_MOVE:
                    float deltaY = event.getY() - initialY;
                    if (deltaY > 0) {
                        isDraggingDown = true;
                        v.setTranslationY(deltaY);
                    }
                    break;
                case MotionEvent.ACTION_UP:
                case MotionEvent.ACTION_CANCEL:
                    if (isDraggingDown) {
                        if (v.getTranslationY() > v.getHeight() / 4) {
                            onBackClicked();
                        } else {
                            v.animate().translationY(0).setDuration(300).start();
                        }
                        isDraggingDown = false;
                    }
                    break;
            }
            return true;
        });
    }

    private void initViews() {
        ivPlayPause = findViewById(R.id.iv_player);
        ivNext = findViewById(R.id.iv_right);
        ivPrev = findViewById(R.id.iv_left);
        ivLoop = findViewById(R.id.iv_xunhuan);
        ivMenu = findViewById(R.id.iv_caidan);
        tvMusicName = findViewById(R.id.tv_musicName);
        tvAuthor = findViewById(R.id.tv_author);
        seekBar = findViewById(R.id.seekBar);
        tvCurrentTime = findViewById(R.id.tv_current_time);
        tvTotalTime = findViewById(R.id.tv_total_time);
        iv_back = findViewById(R.id.iv_back);
        iv_xin = findViewById(R.id.iv_xin);
        drawerLayout = findViewById(R.id.drawer_layout);
        navigationView = findViewById(R.id.nav_view);
        iv_back.setOnClickListener(this);
        iv_xin.setOnClickListener(this);

        View headerView = navigationView.getHeaderView(0);
        tvMusicCount = headerView.findViewById(R.id.tv_music_count);
        tvPlayMode = headerView.findViewById(R.id.tv_play_mode);
        rvMusicList = headerView.findViewById(R.id.rv_music_list);
        rvMusicList.setLayoutManager(new LinearLayoutManager(this));

        // 初始化适配器并设置数据
        musicListAdapter = new MusicListAdapter(musicInfoList, position -> {
            musicInfoList.remove(position);
            musicListAdapter.updateMusicList(musicInfoList);
            updateMusicList();  // 更新音乐列表和播放模式显示
        });
        rvMusicList.setAdapter(musicListAdapter);
    }

    @Override
    protected void onStart() {
        super.onStart();
        // 延迟发布事件，确保 Fragment 已经准备好
        new Handler().postDelayed(() -> {
            EventBus.getDefault().postSticky(new MessageEventCurrentIndexBoolean(musicInfoList, currentIndex, !isPause,playMode)); // 发布事件

            // 在加载图片后，获取其主题色并设置为布局的背景色
            Glide.with(this)
                    .load(musicInfoList.get(currentIndex).getCoverUrl())
                    .into(new SimpleTarget<Drawable>() {
                        @Override
                        public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                            // 将 Drawable 转换为 Bitmap
                            Bitmap bitmap = ((BitmapDrawable) resource).getBitmap();

                            // 使用 Palette 从 Bitmap 中获取主题色
                            Palette.from(bitmap).generate(new Palette.PaletteAsyncListener() {
                                @Override
                                public void onGenerated(@Nullable Palette palette) {
                                    if (palette != null) {
                                        // 获取亮色中的某种颜色
                                        int color = palette.getLightMutedColor(getResources().getColor(android.R.color.white));

                                        // 设置布局背景色
                                        findViewById(R.id.activity_music_player).setBackgroundColor(color);
                                    }
                                }
                            });
                        }
                    });
        }, 100);
    }

    @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        musicInfoList = event.getMusicInfoList();
        if (musicInfoList != null && !musicInfoList.isEmpty()) {
            playMusic(currentIndex);
            updateMusicList();
        }
    }

    @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
    public void onMessageEventB(MessageEvent event) {
        isPause = !isPause;
    }

    private void updateMusicList() {
        tvMusicCount.setText("当前播放: " + musicInfoList.size() + "首");
        tvPlayMode.setText("播放模式: " + getPlayModeText());
        musicListAdapter.updateMusicList(musicInfoList);
    }

    private String getPlayModeText() {
        switch (playMode) {
            case 0:
                return "顺序播放";
            case 1:
                return "随机播放";
            case 2:
                return "单曲循环";
            default:
                return "未知模式";
        }
    }

    private void playMusic(int index) {
        if (musicInfoList == null || musicInfoList.isEmpty() || index >= musicInfoList.size()) {
            return;
        }

        ResponseData.MusicInfo musicInfo = musicInfoList.get(index);
        tvMusicName.setText(musicInfo.getMusicName());
        tvAuthor.setText(musicInfo.getAuthor());

        mediaPlayer.reset();
        try {
            mediaPlayer.setDataSource(musicInfo.getMusicUrl());
            mediaPlayer.prepare();
            mediaPlayer.start();
            isPause = true;
            ivPlayPause.setBackgroundResource(R.drawable.play);
            seekBar.setMax(mediaPlayer.getDuration());
            tvTotalTime.setText(formatTime(mediaPlayer.getDuration()));
            updateSeekBar();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void togglePlayPause() {
        EventBus.getDefault().postSticky(new MessageEventCurrentIndexBoolean(musicInfoList, currentIndex, !isPause,playMode)); // 发布事件
        if (isPause) {
            mediaPlayer.pause();
            isPause = false;
            ivPlayPause.setBackgroundResource(R.drawable.player);
        } else {
            mediaPlayer.start();
            isPause = true;
            ivPlayPause.setBackgroundResource(R.drawable.play);
            updateSeekBar();
        }
    }

    private void playNext() {
        if (playMode == 1) {
            currentIndex = new Random().nextInt(musicInfoList.size());
        } else {
            currentIndex = (currentIndex + 1) % musicInfoList.size();
        }
        playMusic(currentIndex);
        EventBus.getDefault().postSticky(new MessageEventCurrentIndexBoolean(musicInfoList, currentIndex, !isPause,playMode)); // 发布事件
    }

    private void playPrev() {
        if (playMode == 1) {
            currentIndex = new Random().nextInt(musicInfoList.size());
        } else {
            currentIndex = (currentIndex - 1 + musicInfoList.size()) % musicInfoList.size();
        }
        playMusic(currentIndex);
        EventBus.getDefault().postSticky(new MessageEventCurrentIndexBoolean(musicInfoList, currentIndex, !isPause,playMode)); // 发布事件
    }

    private void switchPlayMode() {
        playMode = (playMode + 1) % 3;
        switch (playMode) {
            case 0:
                ivLoop.setBackgroundResource(R.drawable.xunhuan);
                break;
            case 1:
                ivLoop.setBackgroundResource(R.drawable.suiji);
                break;
            case 2:
                ivLoop.setBackgroundResource(R.drawable.xunhuan1);
                break;
        }
        tvPlayMode.setText("播放模式: " + getPlayModeText());
    }

    private void onSongComplete() {
        if (playMode == 2) {
            mediaPlayer.start();
        } else {
            playNext();
        }
    }

    private void updateSeekBar() {
        if (mediaPlayer == null) {
            return; // Ensure mediaPlayer is not null
        }

        if (!isSeekBarChanging) {
            seekBar.setProgress(mediaPlayer.getCurrentPosition());
            tvCurrentTime.setText(formatTime(mediaPlayer.getCurrentPosition()));
        }
        if (isPause) {
            seekBar.postDelayed(this::updateSeekBar, 1000);
        }
        EventBus.getDefault().postSticky(new MessageEventSeekbar(musicInfoList, currentIndex, !isPause, mediaPlayer.getCurrentPosition())); // 发布事件
    }

    private String formatTime(int timeInMillis) {
        int minutes = timeInMillis / 60000;
        int seconds = (timeInMillis % 60000) / 1000;
        return String.format("%02d:%02d", minutes, seconds);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);

        handler.removeCallbacksAndMessages(null); // Stop any pending callbacks
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.iv_back) {
            onBackClicked();
        } else if (v.getId() == R.id.iv_xin) {
            isXin = !isXin;
            xin(isXin);
        }
    }

    private void onBackClicked() {
        findViewById(R.id.activity_music_player).animate()
                .translationY(findViewById(R.id.activity_music_player).getHeight())
                .setDuration(500)
                .withEndAction(() -> {
                    Intent intent = new Intent(MusicPlayerActivity.this, MusicMainActivity.class);
                    startActivity(intent);
                    overridePendingTransition(0, 0);
                })
                .start();
    }

    private void xin(boolean isXin) {
        if (isXin) {
            iv_xin.setImageResource(R.drawable.redxin);
        } else {
            iv_xin.setImageResource(R.drawable.blackxin);
        }
    }
}
